<?php

class User {
	private $user_id;
	private $username;
	private $fullname;
	private $email;
	
	private $permission = array();

	public function __construct($registry) {
		$this->db = $registry->get('db');
		$this->request = $registry->get('request');
		$this->session = $registry->get('session');

		if (isset($this->session->data['user_id'])) {
			$sql = 'SELECT * FROM ' . DB_PREFIX . 'user WHERE user_id = :user_id AND status = \'1\'';
			$user_query = $this->db->query($sql, array(':user_id' => intval($this->session->data['user_id'])));

			if ($user_query->num_rows) {
				$this->user_id = $user_query->row['user_id'];
				$this->username = $user_query->row['username'];
				$this->user_group_id = $user_query->row['user_group_id'];
				$this->fullname = $user_query->row['fullname'];
				$this->email = $user_query->row['email'];
				
				//$this->db->query("UPDATE " . DB_PREFIX . "user SET ip = '" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "' WHERE user_id = '" . (int)$this->session->data['user_id'] . "'");
				$sql = 'UPDATE ' . DB_PREFIX . 'user SET ip = :ip WHERE user_id = :user_id';
				$params = array(
					':ip' => $this->db->escape($this->request->server['REMOTE_ADDR']),
					':user_id' => $this->user_id
				);
				$this->db->query($sql, $params);

				//$user_group_query = $this->db->query("SELECT permission FROM " . DB_PREFIX . "user_group WHERE user_group_id = '" . (int)$user_query->row['user_group_id'] . "'");
				$sql = 'SELECT permission FROM ' . DB_PREFIX . 'user_group WHERE user_group_id = :user_group_id';
				$user_group_query = $this->db->query($sql, array(':user_group_id' => intval($user_query->row['user_group_id'])));

				$permissions = unserialize($user_group_query->row['permission']);
				if (is_array($permissions)) {
					foreach ($permissions as $key => $value) {
						$this->permission[$key] = $value;
					}
				}
			} else {
				$this->logout();
			}
		}
	}

	public function login($username, $password) {
		//$user_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "user WHERE username = '" . $this->db->escape($username) . "' AND (password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1('" . $this->db->escape($password) . "'))))) OR password = '" . $this->db->escape(md5($password)) . "') AND status = '1'");
		$sql = 'SELECT * FROM ' . DB_PREFIX . "user WHERE username = :username AND password = SHA1(CONCAT(salt, SHA1(CONCAT(salt, SHA1(:password))))) AND status = '1'";
		$params = array(
			':username' => $this->db->escape($username),
			':password' => $this->db->escape($password)
		);
		$user_query = $this->db->query($sql, $params);

		if ($user_query->num_rows) {
			$this->session->data['user_id'] = $user_query->row['user_id'];

			$this->user_id = $user_query->row['user_id'];
			$this->username = $user_query->row['username'];
			$this->user_group_id = $user_query->row['user_group_id'];

			//$user_group_query = $this->db->query("SELECT permission FROM " . DB_PREFIX . "user_group WHERE user_group_id = '" . (int)$user_query->row['user_group_id'] . "'");
			$sql = 'SELECT permission FROM ' . DB_PREFIX . 'user_group WHERE user_group_id = :user_group_id';
			$params = array(
				':user_group_id' => (int) $user_query->row['user_group_id']
			);
			$user_group_query = $this->db->query($sql, $params);

			$permissions = unserialize($user_group_query->row['permission']);
			if (is_array($permissions)) {
				foreach ($permissions as $key => $value) {
					$this->permission[$key] = $value;
				}
			}

			return true;
		} else {
			return false;
		}
	}

	public function logout() {
		unset($this->session->data['user_id']);

		$this->user_id = '';
		$this->username = '';
	}

	public function hasPermission($key, $value) {
		if (isset($this->permission[$key])) {
			return in_array($value, $this->permission[$key]);
		} else {
			return false;
		}
	}

	public function isLogged() {
		return $this->user_id;
	}

	public function getId() {
		return $this->user_id;
	}

	public function getUserName() {
		return $this->username;
	}

	public function getGroupId() {
		return $this->user_group_id;
	}
	
	public function getFullName(){
		return $this->fullname;
	}
	
	public function getEmail(){
		return $this->email;
	}

	/*
	 * isManagerOrAdmin
	 * 判断当前运行的后台是manager还是admin
	 * @return 如果是manager，则返回true,
	 */
	public function isManagerOrAdmin() {
		$path = getcwd();
		$path_array = explode('/', $path);
		if (!empty($path_array) && end($path_array) === 'manager') {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * setPermissionFromDb
	 * 根据控制器获取当前权限
	 * @param type 权限类型，目前只有access(查看)，modify(修改)
	 * @param controller_str 指定控制器（可选）。如果为空，则默认获取当前控制器
	 * @return {is_allow_access:true or false,is_allow_modify:true or false}
	 */
	public function hasManagerPermission($type='access',$controller_str=null){
		if($controller_str && !empty($controller_str)){
			$controller = $controller_str;
		}elseif(isset($this->request->get['route']) && !empty ($this->request->get['route'])){
			$part = explode('/', $this->request->get['route']);
			$controller = '';
			if (isset($part[0])) {
				$controller .= $part[0];
			}

			if (isset($part[1])) {
				$controller .= '/' . $part[1];
			}
		}
		if(isset($controller) && !empty($type)){
			$params = array(
				':user_group_id'=>$this->getGroupId(),
				':controller'=>$controller
			);
			
			switch ($type){
				case 'access':
					$sql = 'SELECT `is_allow_access` FROM `rr1_manager_permission` WHERE `user_group_id`=:user_group_id AND `controller`=:controller';
					$row = $this->db->query($sql,$params)->row;
					return !empty($row) && $row['is_allow_access']==1;
				case 'modify':
					$sql = 'SELECT `is_allow_modify` FROM `rr1_manager_permission` WHERE `user_group_id`=:user_group_id AND `controller`=:controller';
					$row = $this->db->query($sql,$params)->row;
					return !empty($row) && $row['is_allow_modify']==1;
			}
		}
		return false;
	}
}
